package cn.jtool.dig.common.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import org.apache.commons.collections4.CollectionUtils;

import java.net.InetSocketAddress;
import java.util.List;

public class CtxUtils {

    public static String getIp(ChannelHandlerContext ctx) {
        return ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
    }
    public static InetSocketAddress getLocalInetSocketAddress(ChannelHandlerContext ctx){
        return (InetSocketAddress)ctx.channel().localAddress();
    }
    public static InetSocketAddress getRemoteInetSocketAddress(ChannelHandlerContext ctx){
        return (InetSocketAddress)ctx.channel().remoteAddress();
    }
    public static String getAddress(ChannelHandlerContext ctx){
        return ctx.channel().remoteAddress().toString();
    }

    public static <T> void setAttribute(ChannelHandlerContext ctx, AttributeKey<T> key, T value){
        ctx.channel().attr(key).set(value);
    }

    public static <T> T getAttribute(ChannelHandlerContext ctx, AttributeKey<T> key){
        return ctx.channel().attr(key).get();
    }

    public static boolean iptables(ChannelHandlerContext ctx, List<String> whiteIps, List<String> blackIps){
        String remoteIp = getRemoteInetSocketAddress(ctx).getHostName();
        if(CollectionUtils.isNotEmpty(whiteIps)){
            return whiteIps.contains(remoteIp);
        }else if(CollectionUtils.isNotEmpty(blackIps)){
            return !blackIps.contains(remoteIp);
        }
        return true;
    }

}
